package com.randev.snap;

import com.randev.snapservices.ImageCounterService;
import com.randev.snapservices.LoginService;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class LoginActivity extends Activity implements OnClickListener{

	EditText txtUserName, txtPassword;
	Button btnSignIn, btnCancel;
	AlertDialog.Builder alertDialog;
	ProgressDialog progressDialog;
	private final String TAG = "LoginActivity";
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        txtUserName = (EditText) findViewById(R.id.etUserName);
        txtPassword = (EditText) findViewById(R.id.etPassword);
        btnSignIn = (Button) findViewById(R.id.bSignIn);
        btnCancel = (Button) findViewById(R.id.bCancel);
        
        btnSignIn.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
        alertDialog = new AlertDialog.Builder(this);
        alertDialog.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
        progressDialog = new ProgressDialog(LoginActivity.this);
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
        if (!prefs.contains("FolderId")) {
        	Editor editor = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
			editor.putString("FolderId", "1");
			editor.commit();
        }        
    }
    
    private boolean validateFields() {
    	boolean check = false;
    	if (!txtUserName.getText().toString().isEmpty()) {
    		if (!txtPassword.getText().toString().isEmpty()) {
    			check = true;
    		} else {
    			check = false;
    			alertDialog.setTitle(LoginActivity.this.getString(R.string.alert));
    			TextView tViewError = new TextView(LoginActivity.this);
    			tViewError.setHeight(90);
    			tViewError.setGravity(Gravity.CENTER_HORIZONTAL);
    			tViewError.setText(LoginActivity.this.getString(R.string.info_password_empty));
    			alertDialog.setView(tViewError);
    			alertDialog.setPositiveButton(LoginActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
    			alertDialog.show();
    			
    			txtPassword.setFocusable(true);
    			txtPassword.requestFocus();
    		}
    	} else {
    		check = false;
    		
    		alertDialog.setTitle(LoginActivity.this.getString(R.string.alert));
			TextView tViewError = new TextView(LoginActivity.this);
			tViewError.setHeight(90);
			tViewError.setGravity(Gravity.CENTER_HORIZONTAL);
			tViewError.setText(LoginActivity.this.getString(R.string.info_username_empty));
			alertDialog.setView(tViewError);
			alertDialog.setPositiveButton(LoginActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			alertDialog.show();
    		txtUserName.setFocusable(true);
    		txtUserName.requestFocus();
    	}
		return check;
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.bSignIn:
			if (validateFields()) {
				if (isNetworkAvailable()) {
					
					String userName = txtUserName.getText().toString();
					String password = txtPassword.getText().toString();
					Log.w(TAG, "username: " + userName);
					Log.w(TAG, "password: " + password);
					
					Intent loginServiceIntent = new Intent(this, LoginService.class);
					Messenger messenger = new Messenger(loginMessengerHandler);
					Messenger progressMessenger = new Messenger(progressHandler);
					Bundle bundle = new Bundle();
					
					bundle.putString("UserName", userName);
					bundle.putString("Password", password);
					try {
						loginServiceIntent.putExtras(bundle);
						loginServiceIntent.putExtra("MESSENGER", messenger);
						loginServiceIntent.putExtra("PROGRESS", progressMessenger);
						startService(loginServiceIntent);
					} catch (SecurityException e) {
						Log.w(TAG, "Unable to start login service: " + e.toString());
					}
				}
			}
			break;
		case R.id.bCancel:
			finish();
			break;
		}
		
	}
	
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
	    
	   
	    boolean networkAvailable = false;
	    
	    if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
	    	networkAvailable = true;
	    } else {
	    	TextView tViewError = new TextView(LoginActivity.this);
	    	tViewError.setGravity(Gravity.CENTER_HORIZONTAL);
	    	tViewError.setHeight(90);
  		  	alertDialog.setView(tViewError);
  		  	tViewError.setText(LoginActivity.this.getString(R.string.error_no_internet_connectivity));
	    	alertDialog.setTitle(LoginActivity.this.getString(R.string.warning));
	    	alertDialog.show();
	    }
	    return networkAvailable;
	}
	
	private Handler loginMessengerHandler = new Handler() {
	    public void handleMessage(Message message) {
	      Bundle resultBundle = message.getData();
	      String result = resultBundle.getString("Result");
	      String key = resultBundle.getString("Key");
	      String status = resultBundle.getString("Status");
	      Log.w("result", result);
	      Log.w("response", key);
	      Log.w("Status", status);
	      
	      if (result.equals("1")) {
	    	  if (status.contentEquals("1")) {
	    		 Log.w("Handler key recieved", key + "");
	    		 
	    		 Log.w("KEY", key + "");
	    		 progressDialog.dismiss();
	    		 
	    		 Intent imageCounterServiceIntent = new Intent(LoginActivity.this, ImageCounterService.class);
	    		 Bundle bundletoImageCounter = new Bundle();
	    		 bundletoImageCounter.putString("Key", key);
	    		 Messenger imageCounterMessenger = new Messenger(imageCountHandler);
	    		 Messenger imageCounterProgressMessenger = new Messenger(imageCounterProgressHandler);
	    		 try {
					imageCounterServiceIntent.putExtras(bundletoImageCounter);
					 imageCounterServiceIntent.putExtra("IMAGECOUNTMESSENGER", imageCounterMessenger);
					 imageCounterServiceIntent.putExtra("IMAGECOUNTERPROGRESS", imageCounterProgressMessenger);
					 startService(imageCounterServiceIntent);
				} catch (SecurityException e) {
					Log.w(TAG, "Unable to start image count service: " + e.toString());
				}
	    		 
	    		 
	    		 
	    	  } else {
	    		  alertDialog.setTitle(LoginActivity.this.getString(R.string.warning));
	    		  TextView tViewError = new TextView(LoginActivity.this);
	    		  tViewError.setGravity(Gravity.CENTER_HORIZONTAL);
	    		  tViewError.setHeight(90);
	    		  alertDialog.setView(tViewError);
	    		  tViewError.setText(LoginActivity.this.getString(R.string.error_invalid_username_or_password));
			      alertDialog.show();
			      progressDialog.dismiss();
	    	  }	    	  
	      } else {
	    	  alertDialog.setTitle(LoginActivity.this.getString(R.string.warning));
	    	  TextView tViewError = new TextView(LoginActivity.this);
    		  tViewError.setGravity(Gravity.CENTER_HORIZONTAL);
    		  tViewError.setHeight(90);
    		  alertDialog.setView(tViewError);
    		  tViewError.setText(LoginActivity.this.getString(R.string.error_validating_username_password));
		      alertDialog.show();
		      progressDialog.dismiss();
	      }

	    };
	  };
	  
	private Handler progressHandler = new Handler() {
	    public void handleMessage(Message message) {
	    	int status = message.arg1;
	    	
	    	switch (status) {
	    	
	    	case 1: 
	    		progressDialog.setMessage(LoginActivity.this.getString(R.string.info_signing_in));
	    		progressDialog.show();
	    		break;
	    		
	    	case 2:
	    		progressDialog.dismiss();
	    		break;
	    	}
	    };
	};
	
	private Handler imageCountHandler = new Handler() {
		public void handleMessage(Message message) {
			Bundle resultFromImageCount = message.getData();
			String imageCount = resultFromImageCount.getString("Response");
			String result = resultFromImageCount.getString("Result");
			Log.w("Imagecoun", imageCount);
			if (result.contentEquals("1")) {
				Editor editor = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
				editor.putString("ImageCount", imageCount);
				editor.commit();
				
				Toast preferenceSaved = Toast.makeText(LoginActivity.this, LoginActivity.this.getString(R.string.info_preference_saved), Toast.LENGTH_SHORT);
				preferenceSaved.show();
				progressDialog.dismiss();
				
				try {
					Intent MainMenuIntent = new Intent(LoginActivity.this, MainMenuActivity.class);
					finish();
					startActivity(MainMenuIntent);
				} catch (ActivityNotFoundException e) {
					Log.w(TAG, "Unable to start MainMenu: " + e.toString());
				}
				
			} else {
				alertDialog.setTitle(LoginActivity.this.getString(R.string.warning));
		    	TextView tViewError = new TextView(LoginActivity.this);
	    		tViewError.setGravity(Gravity.CENTER_HORIZONTAL);
	    		tViewError.setHeight(90);
	    		alertDialog.setView(tViewError);
	    		tViewError.setText(LoginActivity.this.getString(R.string.error_getting_image_count));
			    alertDialog.show();
			    progressDialog.dismiss();
			}
			
			
		};
	};
	
	private Handler imageCounterProgressHandler = new Handler() {
		public void handleMessage(Message message) {
			int status = message.arg1;
	    	
	    	switch (status) {
	    	
	    	case 1: 
	    		progressDialog.setMessage(LoginActivity.this.getString(R.string.info_getting_count));
	    		progressDialog.show();
	    		break;
	    		
	    	case 2:
	    		progressDialog.dismiss();
	    		break;
	    	}
			
		};
		
	};
	  

//    resources:
//    http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
//	  http://www.vogella.com/articles/AndroidJSON/article.html
    
}
